<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="./common.css">
    <script src="https://cdn.bootcdn.net/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
</head>

<body>
    <img data-src="https://img.36krcdn.com/20190808/v2_1565254363234_img_jpg">
    <img data-src="https://img.36krcdn.com/20190905/v2_1567641293753_img_png">
    <img data-src="https://img.36krcdn.com/20190905/v2_1567640518658_img_png">
    <img data-src="https://img.36krcdn.com/20190905/v2_1567642423719_img_000">
    <img data-src="https://img.36krcdn.com/20190905/v2_1567642425030_img_000">
    <img data-src="https://img.36krcdn.com/20190905/v2_1567642425101_img_000">
    <img data-src="https://img.36krcdn.com/20190905/v2_1567642425061_img_000">
    <img data-src="https://img.36krcdn.com/20190904/v2_1567591358070_img_jpg">
    <img data-src="https://img.36krcdn.com/20190905/v2_1567641974410_img_000">
    <img data-src="https://img.36krcdn.com/20190905/v2_1567641974454_img_000">
    <script>

        const imgs = document.getElementsByTagName('img');
        const num = imgs.length;
        let n = 0;
        // document.addEventListener('DOMContentLoaded', () => {
        //     loadImage();
        // })
        function loadImage() {

            // console.log('haha')
            // 是否在可视区？ 
            let screenHeight = document.documentElement.clientHeight;// 一屏高度
            // 滚动条
            // 不同浏览器的兼容性问题
            let scrollTop = document.documentElement.scrollTop
                || document.body.scrollTop;

            for (let i = 0; i < num; i++) {
                // console.log(imgs[i].offsetTop);
                if (imgs[i].offsetTop < screenHeight + scrollTop) {
                    // 数据属性
                    // console.log(imgs[i].dataset.src, imgs[i].dataset.price)
                    imgs[i].src = imgs[i].getAttribute('data-src');
                    n = i + 1;
                    if (n === num) {
                        // console.log('所有图片加载完毕');
                        window.removeEventListener('scroll', throttleLayLoad);
                    }
                }
            }
        }
        const throttleLayLoad = _.throttle(loadImage, 500)
        window.addEventListener('scroll', throttleLayLoad);
        window.addEventListener('scroll', loadImage);
    </script>

</body>

</html>